# -*- coding: utf-8 -*-
# **********************************************************
# * Author        : 赵刚
# * Create time   : 2021/12/13 10:16
# * Description   :
# **********************************************************
import datetime
from urllib.parse import urlparse

import pandas as pd
import requests
from bs4 import BeautifulSoup
from flask import request
from flask.views import MethodView

from api.utils.mssql import MSSQL
from core.dto.ResponseDtos import PoleGuyDataRespnseDTO
from core.dto.success import SuccessDTO
from core.response import Response


class PoleGuyController(MethodView):

    """创建分析任务"""
    @staticmethod
    def get():
        #获取查询参数据
        station_id_args = request.args["station_id"]

        resDto = PoleGuyDataRespnseDTO()
        resDto.datas = []

        # mssql = MSSQL(host='101.201.68.169', user='sa', pwd='sqlserver2008r2**', db='HuanReZhan_DB')
        mssql = MSSQL(host='172.17.181.16', user='sa', pwd='sqlserver2008r2**', db='HuanReZhan_DB')
        # mssql = MSSQL(host='101.201.68.169', user='sa', pwd='sqlserver2008r2**', db='HuanReZhan_DB')

        try:
            timeSearch = datetime.datetime.now().strftime("%Y%m%d")
            # startdate =request.args["startdate"]
            # days = request.args["days"]

            dt = pd.to_datetime(timeSearch)
            sql = """SELECT id,name,[desc],is_used,belongto,station_id,type,settings FROM agriculture_info where type = '%s' and station_id = '%s'""" % ('zhongtie_pole_guy',station_id_args)
            resultsDevice = mssql.ExecQuery(sql)

            if len(resultsDevice) == 0:
                resDto.model = "zhongtie.poleguy.query.fail.model"
                resDto.message = "获取电杆接线设置数据失败"
                resDto.datas = None
                return Response.make_response(resDto, 403)
            else:
                device_id = resultsDevice[0][0]
                device_name = resultsDevice[0][1]
                device_desc = resultsDevice[0][2]
                device_is_used = resultsDevice[0][3]
                device_belongto = resultsDevice[0][4]
                device_station_id = resultsDevice[0][5]
                device_type = resultsDevice[0][6]
                device_settings = resultsDevice[0][7]

                sql = """SELECT id,station_id,data_id,value,created_time FROM real_datas where station_id='%s'""" % device_station_id
                resultsRealData = mssql.ExecQuery(sql)

                if len(resultsRealData) == 0:
                    resDto.model = "zhongtie.poleguy.query.fail.model"
                    resDto.message = "获取电杆接线最新数据失败"
                    resDto.datas = None
                    resDto.id = ''
                    resDto.station_id = ''
                    resDto.data_id = ''
                    resDto.value = ''
                    resDto.created_time = ''
                    return Response.make_response(resDto, 403)
                else:
                    realdata_id = resultsRealData[0][0]
                    realdata_station_id = resultsRealData[0][1]
                    realdata_data_id = resultsRealData[0][2]
                    realdata_value = resultsRealData[0][3]
                    realdata_created_time = resultsRealData[0][4]

                    resDto.id = realdata_id
                    resDto.station_id = realdata_station_id
                    resDto.data_id = realdata_data_id
                    resDto.value = realdata_value

                    #将时间戳转成时间格式
                    #realdata_created_time为datatiime类型变量，将其格式化为日期字符串。
                    resDto.created_time = realdata_created_time.strftime("%Y-%m-%d %H:%M:%S")

                    resDto.model = "zhongtie.poleguy.query.success.model"
                    resDto.message = "获取电杆接线设置数据成功"
                    return Response.make_response(resDto, 200)
        except Exception as ex:
            resDto.model = "zhongtie.poleguy.query.fail.model"
            resDto.message = "获取电杆接线设置数据失败"
            resDto.datas = None
            resDto.id = ''
            resDto.station_id = ''
            resDto.data_id = ''
            resDto.value = ''
            resDto.created_time = ''
            return Response.make_response(resDto, 403)

    """
    电杆接线设置
    """
    @staticmethod
    def put(id):
        resDto = SuccessDTO()

        #获取查询参数据
        #获取body体
        body = request.get_json()

        # mssql = MSSQL(host='101.201.68.169', user='sa', pwd='sqlserver2008r2**', db='HuanReZhan_DB')
        mssql = MSSQL(host='172.17.181.16', user='sa', pwd='sqlserver2008r2**', db='HuanReZhan_DB')

        try:
            dt = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            sql = """INSERT INTO command_info(command_type,command_value,command_time,is_finished,station_id) VALUES('%s','%s','%s','%s','%s')""" % ('change_poleguy_config',str(body).replace("'","\""),dt,0,id)

            mssql.ExecNonQuery(sql)

            resDto.model = "zhongtie.poleguy.config.success.model"
            resDto.datas = None
            resDto.message = '发送设备设置信息成功'
            return Response.make_response(resDto, 200)
        except Exception as ex:
            resDto.model = "zhongtie.poleguy.config.fail.model"
            resDto.message = "发送设备设置信息失败"
            resDto.datas = None
            return Response.make_response(resDto, 403)